<template>
  <a-card
    class="general-card"
    title="APP版本"
    :bordered="false"
  >
    <PickSearchColumn :columns="columnsSearch" @reset="(val) => {apiParams = {...apiParams, ...val}}" @search="(val) => {apiParams = {...apiParams, ...val}}">
    </PickSearchColumn>
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button type="primary" @click="handleAdd">
            添加
          </a-button>
        </a-space>
      </a-col>
    </a-row>
    <PickTablePage
      ref="tablePageRef"
      :columns="columnsTable"
      :methods="sortMethods"
      :api="appVersionPage"
      @delete="handleDelete"
      @editor="handleEdit"
      @detail="seeCashWithdrawal"
      :api-params="apiParams"
      :bordered="true"
    >
      <template #forceUpdate="{ data }">
        <span>{{ data.forceUpdate == false ? '非强制' : '强制' }}</span>
      </template>
      <template #type="{ data }">
        <span>{{ data.type == 'IOS' ? '苹果' : '安卓' }}</span>
      </template>
    </PickTablePage>
    <!-- 添加/编辑modal -->
    <a-modal
      v-model:visible="versionData.enableAddModal"
      :align-center="false"
      :footer="false"
    >
      <template #title> {{ title }} </template>
      <a-form ref="formRef" :model="versionData.form" @submit="handleAddOk">
        <a-form-item
          field="versionName"
          label="版本名称"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-input v-model="versionData.form.versionName" />
        </a-form-item>
        <a-form-item
          field="version"
          label="版本号"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-input v-model="versionData.form.version" />
          <template #extra>
            <span
              >在移动端项目->manifest.json->基础配置->应用版本名称中查看</span
            >
          </template>
        </a-form-item>

        <a-form-item
          field="versionUpdateDate"
          label="更新时间"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-date-picker
            v-model="versionData.form.versionUpdateDate"
            show-time
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item
          field="forceUpdate"
          label="强制更新"
          :validate-trigger="['change']"
        >
          <a-radio-group v-model="versionData.form.forceUpdate" type="button">
            <a-radio :value="true">强制更新</a-radio>
            <a-radio :value="false">非强制更新</a-radio>
          </a-radio-group>
          <template #extra>
            <span v-if="versionData.form.forceUpdate == true"
              >强制更新即为应用中必须更新此版本。不更新则无法继续使用App</span
            >
            <span v-if="versionData.form.forceUpdate == false"
              >非强制更新为应用中推荐更新此版本。不更新还可以继续使用</span
            >
          </template>
        </a-form-item>
        <a-form-item field="type" label="类型">
          <a-radio-group v-model="versionData.form.type" type="button">
            <a-radio value="IOS">苹果</a-radio>
            <a-radio value="ANDROID">安卓</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          field="downloadUrl"
          label="下载地址"
          :rules="[REQUIRED, VARCHAR20]"
          :validate-trigger="['change']"
        >
          <a-input v-model="versionData.form.downloadUrl" />
          <template #extra>
            <span v-if="versionData.form.type == 'IOS'"
              >AppStore中App项目下载目录。可从下载App页面点击分享，拷贝链接</span
            >
            <span v-else>安卓该链接为应用的下载地址</span>
          </template>
        </a-form-item>
        <a-form-item
          field="content"
          label="更新内容"
          :validate-trigger="['change']"
        >
          <!-- <a-input v-model="versionData.form.content" /> -->
          <a-textarea
            v-model="versionData.form.content"
            :max-length="100"
            allow-clear
            show-word-limit
          />
        </a-form-item>
        <a-form-item label="操作">
          <a-button :loading="versionData.formLoading" html-type="submit"
          type="primary">保存</a-button
          >
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 查看 -->
    <a-modal
      v-model:visible="seeWithdrawal"
      :align-center="false"
    >
      <template #title> 查看 </template>
      <a-form
        ref="formRef"
        :style="{ width: '460px' }"
        layout="horizontal"
        auto-label-width
        :model="versionData.form"
      >
        <a-form-item label="版本名称：">
          <span>{{ versionData.form.versionName }}</span>
        </a-form-item>
        <a-form-item label="版本号：">
          <span>{{ versionData.form.version }}</span>
        </a-form-item>
        <a-form-item label="更新时间：">
          <span>{{ versionData.form.versionUpdateDate }}</span>
        </a-form-item>
        <a-form-item label="强制更新：">
          <span>{{
            versionData.form.forceUpdate == false ? '非强制更新' : '强制更新'
          }}</span>
        </a-form-item>
        <a-form-item label="类型：">
          <span>{{ versionData.form.type == 'IOS' ? 'IOS' : '安卓' }}</span>
        </a-form-item>
        <a-form-item label="下载地址：">
          <span>{{ versionData.form.downloadUrl }}</span>
        </a-form-item>
        <a-form-item label="更新内容：">
          <span>{{ versionData.form.content }}</span>
        </a-form-item>
      </a-form>
      <template #footer>
        <div style="text-align: right">
          <a-button type="text" @click="seeWithdrawal = false">取消</a-button>
        </div>
      </template>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
  import { PickSearchColumn, PickTablePage } from '@pickmall/ui-v3-components';
  
  import { SearchRule, MethodsRule, ColumnsDataRule } from '@/types/global';
  import {
    appVersionPage,
    addVersion,
    editVersion,
    deleteVersion,
  } from '@/api/setting';
  import { systemType } from '@/utils/tools';
  import { ref, reactive } from 'vue';
  import { REQUIRED, VARCHAR20 } from '@/utils/validator';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message } from '@arco-design/web-vue';
  import useCurrentInstance from '@/hooks/useCurrentInstance';

  const apiParams = ref({});
  const tablePageRef = ref<any>();
  const title = ref<string>('');
  const formRef = ref<FormInstance>();
  const seeWithdrawal = ref<boolean>(false); // 查看
  // 获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  interface formInterface {
    enableAddModal: boolean;
    formLoading: boolean;
    fid: string | number;
    form: {
      versionName: string;
      version: string;
      type: string;
      downloadUrl: string;
      content: string;
      versionUpdateDate: string;
      forceUpdate: boolean;
      [key:string]: any;
    };
    [key:string]: any;
  }
  const columnsSearch: Array<SearchRule> = [
    {
      label: '系统类型',
      model: 'type',
      disabled: false,

      select: {
        options: systemType,
      },
    },
  ];

  const columnsTable: ColumnsDataRule[] = [
    {
      title: '版本名称',
      dataIndex: 'versionName',
    },
    {
      title: '版本号',
      dataIndex: 'version',
    },

    {
      title: '强制更新',
      dataIndex: 'forceUpdate',
      width: 150,
      slot: true,
      slotTemplate: 'forceUpdate',
    },
    {
      title: '类型',
      dataIndex: 'type',
      slot: true,
      slotTemplate: 'type',
    },
    {
      title: '更新时间',
      dataIndex: 'versionUpdateDate',
    },
  ];

  const sortMethods: MethodsRule = {
    title: '操作',
    width: 300,
    fixed: 'right',
    methods: [
      {
        title: '查看',
        callback: 'detail',
        type:'text',
       status:'success'
      },
      {
        title: '修改',
        callback: 'editor',
        type:'text',
       status:'warning'
      },
      {
        title: '删除',
        callback: 'delete',
        type:'text',
       status:'danger'
      },
    ],
  };
  // 数据集
  const versionData = reactive<formInterface>({
    enableAddModal: false,
    formLoading: false,
    fid: '', // 当前form的ids
    form: {
      versionName: '',
      version: '',
      forceUpdate: false,
      type: 'IOS',
      downloadUrl: '',
      content: '',
      versionUpdateDate: '',
    }, // 表单提交数据
  });
  // 点击添加
  function handleAdd() {
    versionData.enableAddModal = true;
    title.value = '添加APP版本信息';
    versionData.fid = '';
    Object.keys(versionData.form).forEach((key) => {
      versionData.form[key] = '';
    });
  }
  // 添加/修改地址
  async function handleAddOk() {
    // versionData.form.password = this.md5(versionData.form.password);
    const auth = await formRef.value?.validate();
    if (!auth) {
      let res;
      !versionData.fid
        ? (res = await addVersion(versionData.form))
        : (res = await editVersion(versionData.fid, versionData.form));

      if (res.data.success) {
        Message.success(`${versionData.fid ? '修改' : '添加'}成功!`);
        versionData.enableAddModal = false;
        tablePageRef.value.init();
      }
    }
  }
  // 点击修改地址
  function handleEdit(val: any) {
    title.value = '编辑';
    if (val) {
      Object.keys(val.record).forEach((key) => {
        // eslint-disable-next-line no-unused-expressions,no-prototype-builtins
        versionData.form.hasOwnProperty(key)
          ? (versionData.form[key] = val.record[key])
          : '';
      });
      versionData.fid = val.record.id;
      versionData.enableAddModal = true;
    }
  }
  // 回调删除
  function handleDelete(data: any) {
    modal.confirm({
      title: '确认删除',
      content: `您确认要删除么?`,
      alignCenter: false,
      onOk: async () => {
        const res = await deleteVersion(data.record.id);
        if (res.data.success) {
          Message.success('删除成功');
          tablePageRef.value.init();
        }
      },
    });
  }
  // 查看
  const seeCashWithdrawal = (v: any) => {
    versionData.form = v.record;
    seeWithdrawal.value = true;
  };
</script>
